//
//  PersonInforVC.m
//  doubleEduStudents
//
//  Created by 盛洋 on 2021/1/11.
//  Copyright © 2021 shengYang. All rights reserved.
//

#import "PersonInforVC.h"
#import "personInforCell.h"
#import "TZImagePickerController.h"
#import "BTAreaPickViewController.h"
#import "WSDatePickerView.h"
#import "UpLoadImgModel.h"
#import "changePhoneCell.h"

@interface PersonInforVC ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,personInforCellDelegate,BTAreaPickViewControllerDelegate,UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *people_img;
@property (strong, nonatomic) IBOutlet UIButton *change_btn;
@property (strong, nonatomic) IBOutlet UITableView *right_tab;
@property (strong, nonatomic) IBOutlet UIImageView *show_img;

@end

@implementation PersonInforVC{
    NSArray *titleArr;//名称数组
    NSArray *placeHolderArr;
    NSArray *titleArr1;//名称数组
    BOOL isChangePhone;//是否点击
    UIImagePickerController *imagePicker;
    RequestServices *service;
    int _count; // 倒计时数字
    NSTimer *_timer; // 定时器
    UIButton *sendBtn;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    [self.backKuang setHidden:YES];
    [self showBackCenterKuang:[UIImage imageNamed:@"back_center"]];
    self.change_btn.titleLabel.font = AutoLabFont2;
    //修改图像
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeIcon)];
    [self.people_img addGestureRecognizer:tap];
    //保存信息
    [self.change_btn addTarget:self action:@selector(changeInfor) forControlEvents:UIControlEventTouchUpInside];
    self.right_tab.delegate = self;
    self.right_tab.dataSource = self;
    self.right_tab.tableFooterView = [UIView new];
    [self.right_tab registerNib:[UINib nibWithNibName:@"personInforCell" bundle:nil] forCellReuseIdentifier:@"personInforCell"];
     [self.right_tab registerNib:[UINib nibWithNibName:@"changePhoneCell" bundle:nil] forCellReuseIdentifier:@"changePhoneCell"];
    titleArr = [NSArray arrayWithObjects:@"昵称 ",@"姓名 ",@"性别 ",@"生日 ",@"校区 ",@"地址 ", nil];
    placeHolderArr = [NSArray arrayWithObjects:@"请输入您的昵称",@"请输入您的姓名",@"",@"请选择您的生日",@"请选择学校地址",@"请填写学校名称",nil];
    titleArr1 = [NSArray arrayWithObjects:@"手机号",@"验证码", nil];
    isChangePhone = NO;
    service.view = self.view;
    service = [[RequestServices alloc]initWithDelegate:self];
    [service getUserInfor:7000];
    NSLog(@"--%@--",self.requestDic);
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return titleArr.count;
    }else{
        if (isChangePhone == NO) {
            return 1;
        }else{
            return 2;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return Is_iPhone ? 70 : 100;
    }else{
        return Is_iPhone ? 50 : 80;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
    personInforCell *cell = [tableView dequeueReusableCellWithIdentifier:@"personInforCell" forIndexPath:indexPath];
    cell.content_field.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (@available(iOS 13.0, *)) {
        NSAttributedString *attrString1 = [[NSAttributedString alloc] initWithString:placeHolderArr[indexPath.row] attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor],NSFontAttributeName:cell.content_field.font}];
        cell.content_field.attributedPlaceholder = attrString1;
    } else {
        // Fallback on earlier versions
    }
    
    cell.name_lab.text = [NSString stringWithFormat:@"%@",titleArr[indexPath.row]];
    cell.content_field.tag = 9000+indexPath.row;
    cell.content_field.delegate = self;
    if (indexPath.row == 2) {
        [cell.content_field setHidden:YES];
        [cell.man_btn setHidden:NO];
        [cell.woman_btn setHidden:NO];
        cell.delegate = self;
    }else{
        [cell.content_field setHidden:NO];
        [cell.man_btn setHidden:YES];
        [cell.woman_btn setHidden:YES];
    }
    
    if (indexPath.row < 4) {
        [cell.red_lab setHidden:NO];
    }else{
        [cell.red_lab setHidden:YES];
    }
    
    if (indexPath.row == 5) {
        cell.name_lab.textColor = [UIColor clearColor];
    }else{
        cell.name_lab.textColor = [UIColor whiteColor];
    }
    
    if (indexPath.row == 0) {
        cell.tip_lab.textColor = [UIColor clearColor];
        [cell.content_field setUserInteractionEnabled:YES];
        cell.content_field.borderStyle = UITextBorderStyleRoundedRect;
        [cell.changetel_btn setHidden:YES];
        if (self.requestDic[@"userName"]) {
            cell.content_field.text = [NSString stringWithFormat:@"%@",self.requestDic[@"userName"]];
        }
        
    }else if (indexPath.row == 1) {
        cell.tip_lab.textColor = [UIColor clearColor];
        [cell.content_field setUserInteractionEnabled:YES];
        cell.content_field.borderStyle = UITextBorderStyleRoundedRect;
        [cell.changetel_btn setHidden:YES];
        if (self.requestDic[@"realName"]) {
            cell.content_field.text = [NSString stringWithFormat:@"%@",self.requestDic[@"realName"]];
        }
        
    }else if (indexPath.row == 2){
        cell.tip_lab.textColor = [UIColor clearColor];
        cell.content_field.text = @"";
        cell.content_field.borderStyle = UITextBorderStyleRoundedRect;
        [cell.changetel_btn setHidden:YES];
        if ([self.requestDic[@"gender"] intValue] == 1) {
            [cell.man_btn setImage:[UIImage imageNamed:@"dot_icon_s"] forState:UIControlStateNormal];
        }else if ([self.requestDic[@"gender"] intValue] == 2){
            [cell.woman_btn setImage:[UIImage imageNamed:@"dot_icon_s"] forState:UIControlStateNormal];
            ;
        }
    }
   else if (indexPath.row == 3) {
       cell.tip_lab.textColor = [UIColor clearColor];
        [cell.content_field setUserInteractionEnabled:NO];
        cell.content_field.borderStyle = UITextBorderStyleRoundedRect;
        [cell.changetel_btn setHidden:YES];
       if (self.requestDic[@"birthday"]) {
           cell.content_field.text = [NSString stringWithFormat:@"%@",self.requestDic[@"birthday"]];
        }
        
    }else if (indexPath.row == 4) {
//        cell.tip_lab.text = @"(选填)";
        cell.tip_lab.textColor = Base_lineColor;
        [cell.content_field setUserInteractionEnabled:NO];
        cell.content_field.borderStyle = UITextBorderStyleRoundedRect;
        [cell.changetel_btn setHidden:YES];
        if (self.requestDic[@"province"]){
            cell.content_field.text = [NSString stringWithFormat:@"%@%@%@",self.requestDic[@"province"],self.requestDic[@"city"],self.requestDic[@"area"]];
        }
    }else if (indexPath.row == 5) {
        cell.tip_lab.textColor = [UIColor clearColor];
        [cell.content_field setUserInteractionEnabled:YES];
        cell.content_field.borderStyle = UITextBorderStyleRoundedRect;
        [cell.changetel_btn setHidden:YES];
        if (self.requestDic[@"schoolName"]){
            cell.content_field.text = [NSString stringWithFormat:@"%@",[self.requestDic valueForKey:@"schoolName"]];
        }else{
            cell.content_field.text = @"";
        }
    }
    return cell;
        }
    changePhoneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"changePhoneCell" forIndexPath:indexPath];
    cell.content_field.delegate = self;
    cell.content_field.tag = 10000+indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.name_lab.text = titleArr1[indexPath.row];
    if (indexPath.row == 0) {
        
        [cell.change_btn addTarget:self action:@selector(changePhone:) forControlEvents:UIControlEventTouchUpInside];
        if (isChangePhone == NO) {
            [cell.change_btn setTitle:@"更改" forState:UIControlStateNormal];
            [cell.content_field setUserInteractionEnabled:NO];
        }else{
            [cell.content_field setUserInteractionEnabled:YES];
            [cell.change_btn setTitle:@"取消" forState:UIControlStateNormal];
        }
        
        NSString *str = [NSString stringWithFormat:@"%@",self.requestDic[@"mobile"]];
        if (str.length > 10) {
            NSString *str1 = [str substringToIndex:3];
            NSString *str2 = [str substringFromIndex:str.length - 4];
            str = [NSString stringWithFormat:@"%@****%@",str1,str2];
        }
        
        if (self.requestDic[@"mobile"]){
            if (isChangePhone == NO) {
                cell.content_field.text = str;
            }else{
                cell.content_field.text = self.requestDic[@"mobile"];
            }
        }else{
            cell.content_field.text = @"";
        }
    }else{
        [cell.change_btn setTitle:@"获取验证码" forState:UIControlStateNormal];
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor],NSFontAttributeName:AutoLabFont3}];
        cell.content_field.attributedPlaceholder = attrString;
        [cell.change_btn addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
        sendBtn = cell.change_btn;
    }
    return cell;
}

//修改手机号
-(void)changePhone:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        isChangePhone = YES;
     
    }else{
        isChangePhone = NO;
        [_timer invalidate];
    }
    [_right_tab reloadData];
}

//获取验证码
-(void)getCode:(UIButton *)sender{
    UITextField *field = [self.view viewWithTag:10000];
    [field resignFirstResponder];
    if (field.text.length != 11) {
        [self ShowNewMsg:@"请输入正确的手机号码"];
        return;
    }
    [service getMobileCode:field.text type:@"1" tag:8005];
}


#pragma mark ---- personInforCellDelegate
//选择男
-(void)chooseMan:(UIButton *)sender{
    [self.view endEditing:YES];
    [self.requestDic setValue:@"1" forKey:@"gender"];
}

//选择女
-(void)chooseWoman:(UIButton *)sender{
    [self.view endEditing:YES];
    [self.requestDic setValue:@"2" forKey:@"gender"];
}


//field编辑
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == 9000) {
        [self.requestDic setValue:textField.text forKey:@"userName"];
    }else if (textField.tag == 9001){
        [self.requestDic setValue:textField.text forKey:@"realName"];
    }else if (textField.tag == 9005){
        [self.requestDic setValue:textField.text forKey:@"schoolName"];
    }else if (textField.tag == 10000){
        [self.requestDic setValue:textField.text forKey:@"mobile"];
    }else if (textField.tag == 10001){
        [self.requestDic setValue:textField.text forKey:@"captcha"];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

-(void)getFinished:(NSDictionary *)obj tag:(long long)tag{
    if (tag == 7000) {
        [self.people_img setCornerToCircleWidth:5 color:[UIColor colorWithHexString:@"0XD238D8"]];
        [self.people_img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.requestDic[@"avatarUrl"]]] placeholderImage:DefaultIcon];
    }
    
    if (tag == 8000) {
        //获取图像url
        NSArray *imgArr = [UpLoadImgModel mj_objectArrayWithKeyValuesArray:obj];
        UpLoadImgModel *model = imgArr[0];
        [self.requestDic setValue:model.url forKey:@"avatarUrl"];
    }
    
    if (tag == 8005) {
        //发送验证码
           _count = 60;
           [self handleTimer];
           _timer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
       }
    
    if (tag == 8001) {
        [self ShowNewMsg:@"保存个人信息成功"];
    }
}


- (void)handleTimer
{

    if (_count > 0) {
        [sendBtn setUserInteractionEnabled:NO];
        [sendBtn setTitle:[NSString stringWithFormat:@"%ds",_count] forState:UIControlStateNormal];
        
    } else {
        [sendBtn setUserInteractionEnabled:YES];
        [sendBtn setTitle:[NSString stringWithFormat:@"重发验证码"] forState:UIControlStateNormal];
        
        [_timer invalidate];
    }
    _count -= 1;
}

#pragma mark ----- 保存信息
-(void)changeInfor{
    [self.view endEditing:YES];
    NSLog(@"信息:%@--",self.requestDic);
    [service updateUserInfor:self.requestDic tag:8001];
}

//换图像
-(void)changeIcon{
    [self.view endEditing:YES];
    [self IsCanUseCamera];
}

- (BOOL)IsCanUseCamera
{
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        self.view.backgroundColor = [UIColor colorWithHexString:@"999999"];
        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您未开启相机权限,是否去开启" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去开启", nil];
        view.delegate = self;
        [view show];
        return NO;
    }
    [self openPhoto];
    return YES;
}

- (void)openPhoto {
    //1.判断相册是否可以打开
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return;
    }
    
    //解决在6P上选取相册时取消按钮不好点击问题
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1  delegate:self];
    imagePickerVc.delegate = self;
    //是否允许选择视频
    imagePickerVc.allowPickingMultipleVideo = YES;
    //弹出全屏
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    //设置导航栏背景色
    CGSize tempNavSize = CGSizeMake(SCREEN_W, StatusBarAndNavHeight);
    [imagePickerVc.navigationBar setBackgroundImage:[self imageWithColor:[UIColor colorWithHexString:@"#130A31"] size:tempNavSize] forBarMetrics:UIBarMetricsDefault];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos) {
            [self.people_img setCornerToCircleWidth:5 color:[UIColor colorWithHexString:@"0XD238D8"]];
            [self.people_img setImage:photos[0]];
            [self->service upLoadFile:photos tag:8000];
        }
    }];
    [self.navigationController presentViewController:imagePickerVc animated:YES completion:nil];
}

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    
    if (indexPath.row == 3) {
        WSDatePickerView *datepicker = [[WSDatePickerView alloc]initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *date) {
            NSString *dateStr = [date stringWithFormat:@"yyyy-MM-dd"];
            [self->_requestDic setValue:dateStr forKey:@"birthday"];
            UITextField *field = [self.view viewWithTag:9003];
            field.text = [NSString stringWithFormat:@"%@",dateStr];
        }];
        datepicker.doneButtonColor = [UIColor colorWithHexString:Select_line_Color];
        [datepicker show];
    }
    if (indexPath.row == 4) {
        //选择地址
        BTAreaPickViewController * vc = [[BTAreaPickViewController alloc]initWithDragDismissEnabal:YES];
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

#pragma mark - BTAreaPickViewControllerDelegate

- (void)areaPickerView:(BTAreaPickViewController *)areaPickerView doneAreaModel:(BTAreaPickViewModel *)model{
    UITextField *field = [self.view viewWithTag:9004];
    if ([model.selectedCitie.name isEqualToString:@"市辖区"]) {
        model.selectedCitie.name = @"";
    }
    field.text = [NSString stringWithFormat:@"%@%@%@",model.selectedProvince.name,model.selectedCitie.name,model.selectedArea.name];
    [self.requestDic setValue:model.selectedProvince.name forKey:@"province"];
    [self.requestDic setValue:model.selectedCitie.name forKey:@"city"];
    [self.requestDic setValue:model.selectedArea.name forKey:@"area"];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
